import React, { useEffect } from 'react';
import { Form, Input, Row, Col, message } from "antd";
import { levelRule } from '@/utils/rules/levelRule';
import levelList from '@/staticLists/levelList';
import { useDispatch, useSelector } from "umi"

import $http from "@/services";

export default function index({ levelDetail, _initLevelList }) {
    const [form] = Form.useForm();
    const dispatch = useDispatch();
    // 初始化重置,因为其Form表单中不会监听数据，数据发生变化时不知请，需要进行重置
    useEffect(() => {
        form.resetFields();
    }, [levelDetail])
    //提交新的value
    const onSubmitNewValue = async (item) => {
        let oldValue = levelDetail[item.itemName];
        // 看是否为其搜索中传过来的若为则会传递id值过来
        const newValue = item._id ? item._id : form.getFieldValue(item.itemName);
        // 其try,catch无法捕捉到其规则错误
        const err = form.getFieldsError();
        const isError = err.some(el => el.errors.length > 0);
        if (isError) {
            form.setFieldsValue({ [item.itemName]: staffDetail[item.itemName] });
            return;
        }
        // 判断是否一致
        if (oldValue === newValue) return;
        updateLevelDetail(item.itemName, newValue);
    }


    // 更新level等级级别的
    const updateLevelDetail = async (type, updateVal) => {
        const { data, msg } = await $http.updateLevel({
            _id: levelDetail._id,
            type,
            updateVal
        })
        if (data) return;
        message.success(msg);
        dispatch({
            type: "staff/getDetailLevel",
            payload: levelDetail._id
        })
        _initLevelList();
    }
    return (
        <Form
            layout='vertical'
            form={form}
        >
            {levelList.map((el, index) => {
                return (<Row justify={"space-between"} key={index}>
                    {el.map((item, childIndex) => {
                        return (<Col span={11} key={childIndex}>
                            <Form.Item
                                label={item.labelTxt}
                                name={item.itemName}
                                rules={levelRule[item.itemName]}
                            >
                                <Input
                                    placeholder={item.initVal}
                                    key={item._id}
                                    onBlur={() => onSubmitNewValue(item)}></Input>
                            </Form.Item>
                        </Col>)
                    })}
                </Row>)
            })}

        </Form>

    )
}
